package com.feidee.data.report.controller;

import com.feidee.data.report.model.multidimensional_analysis.MultiDimAnalysisMetaReq;
import com.feidee.data.report.model.multidimensional_analysis.MultiDimAnalysisQueryReq;
import com.feidee.data.report.model.multidimensional_analysis.MultiDimAnalysisRsp;
import com.feidee.data.report.service.MultidimensionalAnalysisService;
import com.feidee.fdcommon.authorization.AuthorizationVerify;
import com.feidee.fdcommon.authorization.model.AuthorizationModel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 多维分析相关接口
 */
@Controller
@RequestMapping("/multiDimAnalysis")
public class MultidimensionalAnalysisController {

  private static final Logger LOGGER = LoggerFactory.getLogger(MultidimensionalAnalysisController.class);

  @Autowired
  private MultidimensionalAnalysisService multidimensionalAnalysisService;

  @RequestMapping("/query")
  @ResponseBody
  public MultiDimAnalysisRsp query(@RequestParam String data, HttpServletRequest request, HttpServletResponse response)
          throws SQLException {
    AuthorizationModel<MultiDimAnalysisQueryReq> verifyResult = AuthorizationVerify.verify(request, data,
            300, MultiDimAnalysisQueryReq.class);
    if (verifyResult.getCode() != 0) return MultiDimAnalysisRsp.Builder.buildAuthError(verifyResult.getErrMsg());
    LOGGER.info("多维分析查询请求：{}", verifyResult.getData());
    MultiDimAnalysisQueryReq req = verifyResult.getData();
    if (req.getDims() == null || req.getDims().isEmpty())
      return MultiDimAnalysisRsp.Builder.buildGenericError("维度不能为空");
    if (req.getDbAndTable() == null || req.getDbAndTable().isEmpty())
      return MultiDimAnalysisRsp.Builder.buildGenericError("表名不能为空");
    if (req.getIndicators() != null && !req.getIndicators().isEmpty()) {
      // 没有聚合函数，则默认使用sum
      List<String> indicators = req.getIndicators();
      for (int i = 0; i < req.getIndicators().size(); i++) {
        if ((!indicators.get(i).contains("(")) || (!indicators.get(i).contains(")"))) {
          indicators.set(i, "sum(" + indicators.get(i) + ") as " + indicators.get(i));
        } else {
          indicators.set(i, indicators.get(i) + " as " + StringUtils.substringBetween(indicators.get(i), "(", ")"));
        }
      }
    }
    return MultiDimAnalysisRsp.Builder.buildSuccess(multidimensionalAnalysisService.query(req));
  }

  @RequestMapping("/meta")
  @ResponseBody
  public MultiDimAnalysisRsp upsertMeta(@RequestParam String data, HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException, TimeoutException {
    AuthorizationModel<MultiDimAnalysisMetaReq> verifyResult = AuthorizationVerify.verify(request, data,
            300, MultiDimAnalysisMetaReq.class);
    if (verifyResult.getCode() != 0) return MultiDimAnalysisRsp.Builder.buildAuthError(verifyResult.getErrMsg());
    MultiDimAnalysisMetaReq req = verifyResult.getData();
    if (req.getDims() == null || req.getDims().isEmpty())
      return MultiDimAnalysisRsp.Builder.buildGenericError("维度不能为空");
    if (StringUtils.isEmpty(req.getDbAndTable()))
      return MultiDimAnalysisRsp.Builder.buildGenericError("表名不能为空");
    LOGGER.info("多维分析元数据请求：{}", verifyResult.getData());
    return MultiDimAnalysisRsp.Builder.buildSuccess(multidimensionalAnalysisService.upsertMeta(verifyResult.getData()));
  }
}
